<template>
  <div class="article-container">
    <div v-if="loading" class="loading">
      <el-skeleton :rows="10" animated />
    </div>
    <div v-else-if="error" class="error">
      <el-empty description="加载失败，请稍后重试" />
      <el-button type="primary" @click="fetchArticle">重新加载</el-button>
    </div>
    <div v-else class="article-content">
      <!-- <h1 class="article-title">{{ article.title }}</h1>
      <div class="article-image" v-if="article.image">
        <img :src="getImageUrl(article.image)" alt="文章图片">
      </div> -->
      <div class="article-body" v-html="article.content"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { commonApi, BASE_URL } from '../api/index.js'

// 获取路由参数
const route = useRoute()

// 文章数据
const article = ref({
  id: 0,
  title: '',
  image: '',
  content: '',
  createtime: 0,
  updatetime: 0
})

// 加载状态
const loading = ref(true)
const error = ref(false)

// 获取文章数据
const fetchArticle = async () => {
  loading.value = true
  error.value = false
  
  try {
    // 从路由参数获取文章ID
    const articleId = route.params.id
    
    if (!articleId) {
      error.value = true
      console.error('文章ID不存在')
      return
    }
    
    const response = await commonApi.getArticle(articleId)
    
    if (response.code === 1 && response.data) {
      article.value = response.data
    } else {
      error.value = true
      console.error('获取文章失败:', response.msg)
    }
  } catch (err) {
    error.value = true
    console.error('获取文章异常:', err)
  } finally {
    loading.value = false
  }
}

// 处理图片URL
const getImageUrl = (path) => {
  if (!path) return ''
  
  // 如果路径已经是完整URL，则直接返回
  if (path.startsWith('http://') || path.startsWith('https://')) {
    return path
  }
  
  // 否则拼接基础URL
  return BASE_URL + path
}

// 组件挂载时获取文章
onMounted(() => {
  fetchArticle()
})
</script>

<style scoped>
.article-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.loading, .error {
  padding: 40px 0;
  text-align: center;
}

.article-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: center;
}

.article-image {
  margin-bottom: 20px;
  text-align: center;
}

.article-image img {
  max-width: 100%;
  border-radius: 4px;
}

.article-body {
  line-height: 1.6;
}

.article-body :deep(img) {
  max-width: 100%;
  height: auto;
}

.article-body :deep(p) {
  margin-bottom: 16px;
}
</style>